<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
	var remote = {
		getPost: function(url, callback) {
			// http://blog.trailimage.com/2011/03/indian-hot-springs-getting-there.html
			// http://code.google.com/apis/blogger/docs/2.0/developers_guide_protocol.html
			// get specific post from blog
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(data) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						//var data = JSON.parse(xhr.responseText);
						callback(xhr.responseText);
					} else {
						callback(null);
					}
				}
			}
			console.log('loading ' + url);
			xhr.open('GET', url, true);
			xhr.send();
		},
		getList: function(id, callback) {
			// get the list of posts at the given blog
			var url = 'http://www.blogger.com/feeds/' + id + '/posts/default';
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(data) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200 && xhr.responseXML) {
						parsePosts(xhr.responseXML, callback);
					} else {
						callback(null);
					}
				}
			}
			console.log('loading ' + url);
			xhr.open('GET', url, true);
			xhr.send();
		}
	};
	
	chrome.extension.onRequest.addListener(function(request, sender, callback) {
		remote[request.action](request.id, callback);
	});
	
	function parsePosts(xml, callback) {
		var posts = [];
		var entries = xml.getElementsByTagName('entry');
		for (var i = 0; i < entries.length; i++) {
			posts.push({
				'title': entries[i].getElementsByTagName('title')[0].textContent,
				'url': getPostUrl(entries[i])
			});
		}
		callback(posts);
	}
	
	function getPostUrl(entry) {
		var links = entry.getElementsByTagName('link');
		for (var i = 0; i < links.length; i++) {
			if (links[i].getAttribute('rel') == 'alternate') {
				return links[i].getAttribute('href');
			}
		}
		return null;
	}
</script>
</body>
</html>